package com.example.smartagrisys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartagrisys.entity.Fertilizer;
import com.example.smartagrisys.entity.FertilizerInventory;
import com.example.smartagrisys.mapper.FertilizerInventoryMapper;
import com.example.smartagrisys.mapper.FertilizerMapper;
import com.example.smartagrisys.service.FertilizerInventoryService;
import com.example.smartagrisys.vo.FertilizerInventoryVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 肥料库存服务实现类
 */
@Service
@RequiredArgsConstructor
public class FertilizerInventoryServiceImpl extends ServiceImpl<FertilizerInventoryMapper, FertilizerInventory> implements FertilizerInventoryService {

    private final FertilizerMapper fertilizerMapper;

    @Override
    public List<FertilizerInventoryVO> getInventoryByFarmerId(Long farmerId) {
        // 查询农户的肥料库存
        LambdaQueryWrapper<FertilizerInventory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FertilizerInventory::getFarmerId, farmerId);
        List<FertilizerInventory> inventoryList = this.list(wrapper);
        
        if (inventoryList.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取所有肥料ID
        List<Long> fertilizerIds = inventoryList.stream()
                .map(FertilizerInventory::getFertilizerId)
                .collect(Collectors.toList());
        
        // 查询肥料信息
        LambdaQueryWrapper<Fertilizer> fertilizerWrapper = new LambdaQueryWrapper<>();
        fertilizerWrapper.in(Fertilizer::getId, fertilizerIds);
        List<Fertilizer> fertilizers = fertilizerMapper.selectList(fertilizerWrapper);
        
        // 将肥料信息映射为Map，方便后续使用
        Map<Long, Fertilizer> fertilizerMap = fertilizers.stream()
                .collect(Collectors.toMap(Fertilizer::getId, Function.identity()));
        
        // 转换为VO对象
        List<FertilizerInventoryVO> result = new ArrayList<>();
        for (FertilizerInventory inventory : inventoryList) {
            FertilizerInventoryVO vo = new FertilizerInventoryVO();
            BeanUtils.copyProperties(inventory, vo);
            
            // 设置肥料相关信息
            Fertilizer fertilizer = fertilizerMap.get(inventory.getFertilizerId());
            if (fertilizer != null) {
                vo.setFertilizerName(fertilizer.getName());
                vo.setFertilizerType(fertilizer.getType());
            }
            
            // 计算总价值
            if (inventory.getQuantity() != null && inventory.getPrice() != null) {
                vo.setTotalValue(inventory.getQuantity().multiply(inventory.getPrice()).setScale(2, RoundingMode.HALF_UP));
            }
            
            result.add(vo);
        }
        
        return result;
    }

    @Override
    public Long addInventory(FertilizerInventory inventory) {
        this.save(inventory);
        return inventory.getId();
    }

    @Override
    public boolean updateInventory(Long id, FertilizerInventory inventory) {
        inventory.setId(id);
        return this.updateById(inventory);
    }

    @Override
    public boolean deleteInventory(Long id) {
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean checkAndUpdateInventory(Long farmerId, Long fertilizerId, BigDecimal quantity) {
        // 查询农户的该肥料库存
        LambdaQueryWrapper<FertilizerInventory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FertilizerInventory::getFarmerId, farmerId)
               .eq(FertilizerInventory::getFertilizerId, fertilizerId);
        
        FertilizerInventory inventory = this.getOne(wrapper);
        
        // 检查库存是否足够
        if (inventory == null || inventory.getQuantity().compareTo(quantity) < 0) {
            return false;
        }
        
        // 更新库存
        inventory.setQuantity(inventory.getQuantity().subtract(quantity));
        return this.updateById(inventory);
    }

    @Override
    public FertilizerInventoryVO getInventoryById(Long id) {
        FertilizerInventory inventory = this.getById(id);
        if (inventory == null) {
            return null;
        }
        
        FertilizerInventoryVO vo = new FertilizerInventoryVO();
        BeanUtils.copyProperties(inventory, vo);
        
        // 查询肥料信息
        Fertilizer fertilizer = fertilizerMapper.selectById(inventory.getFertilizerId());
        if (fertilizer != null) {
            vo.setFertilizerName(fertilizer.getName());
            vo.setFertilizerType(fertilizer.getType());
        }
        
        // 计算总价值
        if (inventory.getQuantity() != null && inventory.getPrice() != null) {
            vo.setTotalValue(inventory.getQuantity().multiply(inventory.getPrice()).setScale(2, RoundingMode.HALF_UP));
        }
        
        return vo;
    }
} 